﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.IO;

namespace MII_FIF.Layouts.MII_FIF
{
    public partial class Download : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                string DocumentLibrarySite = Configuration.DocLibName();
                string links = Context.Request.QueryString["links"].ToString();
                string filename = links.Substring(links.LastIndexOf("/")+1, links.Length - links.LastIndexOf("/")-1);
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment; filename=" + filename);
                SPSite site = new SPSite(links);
                SPWeb web = site.OpenWeb();
                SPFile defile = web.GetFile(links);
                byte[] Filebinary = defile.OpenBinary();
                Response.BinaryWrite(Filebinary);
                Response.ContentType = filename.Substring(filename.LastIndexOf("."), filename.Length - filename.LastIndexOf("."));
                Response.Flush();
                Response.End();
            });
        }

        private byte[] StreamFile(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            // Create a byte array of file stream length   
            byte[] ImageData = new byte[fs.Length];
            //Read block of bytes from stream into the byte array   
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
            //Close the File Stream   
            fs.Close();
            return ImageData;
            //return the byte data
        }
    }
}
